package com.hwadee.property.controller.parking;

import com.hwadee.property.dto.ParkingUsePersonal;
import com.hwadee.property.pojo.Parking;
import com.hwadee.property.pojo.ParkingUse;
import com.hwadee.property.service.IParkingService;
import com.hwadee.property.service.IParkingUseService;
import com.hwadee.property.service.IUserService;
import com.hwadee.property.util.AjaxResult;
import com.hwadee.property.util.DateUtil;
import com.hwadee.property.util.JwtUtil;
import com.hwadee.property.dto.PageResult;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/parking-use")
@Api(tags = "车位使用管理-ParkingUseController")
@CrossOrigin
public class ParkingUseController {

    @Autowired
    private IParkingUseService parkingUseService;

    @Autowired
    private IParkingService parkingService;

    @Autowired
    private IUserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 查询本人的所有车位使用记录
     */
    @GetMapping("/personal")
    @ApiOperation(value = "【用户】查询本人车位使用记录", notes = "获取本人车位使用记录")
    public AjaxResult getAllParkingUsesPersonal(@RequestHeader("Authorization") String token) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 根据用户ID查询车位使用信息
            List<ParkingUsePersonal> parkingUses = parkingUseService.getByOwner(userId);

            // 返回车位使用信息
            return AjaxResult.success(parkingUses);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("查询车位使用信息失败");
        }
    }

    /**
     * 新增申请使用车位
     */
    @PostMapping("/applyForParking")
    @ApiOperation(value = "【用户】申请车位使用", notes = "用户申请车位使用。每个用户只能申请一个车位，该车位属于其账号绑定的小区。")
    public AjaxResult applyForParking(
            @RequestHeader("Authorization") String token,

            @ApiParam(value = "车牌号", example = "1")
            @RequestParam String carNumber,

            @ApiParam(value = "使用类型", example = "月租")
            @RequestParam String useType,

            @ApiParam(value = "开始使用时间", example = "2025-1-1 00:00:00")
            @RequestParam
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 准备相关参数
            Parking parking = parkingService.getFreeParking(userService.getById(userId).getCommunityId());
            if (parking == null) return AjaxResult.fail("无空闲车位");
            Long parkingID = parking.getId();
            Double totalFee = parkingUseService.calculateTotalFee(useType, parking.getCommunityId());
            String endTime = DateUtil.dateToString(parkingUseService.getEndUseTime(DateUtil.stringToDate(startTime), useType));

            // 返回申请结果
            parking.setStatus("已占用");
            parkingService.updateById(parking);
            DateUtil.stringToDate(endTime);
            return addParkingUse(token, userId, carNumber, parkingID, useType, totalFee, startTime, endTime);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("申请车位使用失败");
        }
    }

    @GetMapping("/property/page")
    @ApiOperation(value = "【物业】获取车位使用分页列表", notes = "根据筛选条件查询车位使用的分页数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页", required = true, dataType = "int", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = true, dataType = "int", paramType = "query", defaultValue = "10"),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "carNumber", value = "车牌号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parkingId", value = "车位ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "useType", value = "使用类型", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "date", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "date", paramType = "query")
    })
    public AjaxResult getPage(
            @RequestHeader("Authorization") String token,
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "ownerId", required = false) Long ownerId,
            @RequestParam(value = "carNumber", required = false) String carNumber,
            @RequestParam(value = "parkingId", required = false) Long parkingId,
            @RequestParam(value = "useType", required = false) String useType,
            @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        // 如果token为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 调用查询函数
            return getPage(token, current, size, ownerId, carNumber, parkingId,
                    userService.getById(userId).getCommunityId(), useType, startTime, endTime);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("更新车位失败");
        }
    }

    /**
     * 获取车位使用分页列表
     */
    @GetMapping("/page")
    @ApiOperation(value = "【管理员】获取车位使用分页列表", notes = "根据筛选条件查询车位使用的分页数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页", required = true, dataType = "int", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = true, dataType = "int", paramType = "query", defaultValue = "10"),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "carNumber", value = "车牌号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parkingId", value = "车位ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "communityId", value = "小区ID", dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "useType", value = "使用类型", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "date", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "date", paramType = "query")
    })
    public AjaxResult getPage(@RequestHeader("Authorization") String token,
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "carNumber", required = false) String carNumber,
            @RequestParam(value = "parkingId", required = false) Long parkingId,
            @RequestParam(value = "communityId", required = false) Long communityId,
            @RequestParam(value = "useType", required = false) String useType,
            @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        PageResult<ParkingUse> result = parkingUseService.getPage(current, size, userId, carNumber, parkingId, communityId, useType, startTime, endTime);
        return AjaxResult.success(result);
    }

    /**
     * 查询所有车位使用记录
     */
    @GetMapping
    @ApiOperation(value = "【管理员】查询所有车位使用记录", notes = "获取所有车位使用记录")
    public AjaxResult getAllParkingUses(@RequestHeader("Authorization") String token) {
        List<ParkingUse> parkingUses = parkingUseService.list();
        return AjaxResult.success(parkingUses);
    }

    /**
     * 根据ID查询车位使用记录
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "【管理员】根据ID查询车位使用记录", notes = "根据ID获取车位使用记录")
    public AjaxResult getParkingUseById(@RequestHeader("Authorization") String token,
            @ApiParam(value = "车位使用ID", required = true) @PathVariable Long id) {
        ParkingUse parkingUse = parkingUseService.getById(id);
        List<ParkingUse> parkingUses = new ArrayList<>();
        return parkingUse != null ? AjaxResult.success(parkingUses) : AjaxResult.fail("未找到相关车位使用记录");
    }

    /**
     * 新增车位使用记录
     */
    @PostMapping("/{userId}")
    @ApiOperation(value = "【管理员】新增车位使用记录", notes = "新增一条车位使用记录")
    public AjaxResult addParkingUse(@RequestHeader("Authorization") String token,
            @ApiParam(value = "用户ID", required = true, example = "1")
            @PathVariable Long userId,

            @ApiParam(value = "车牌号", example = "1")
            @RequestParam String carNumber,

            @ApiParam(value = "车位ID", example = "1")
            @RequestParam Long parkingId,

            @ApiParam(value = "使用类型", example = "月租")
            @RequestParam String useType,

            @ApiParam(value = "总费用", example = "158.5")
            @RequestParam Double totalFee,

            @ApiParam(value = "开始使用时间", example = "2025-1-1 00:00:00")
            @RequestParam
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime,

            @ApiParam(value = "使用结束时间", example = "2025-1-2 12:00:00")
            @RequestParam
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) throws ParseException {
        ParkingUse parkingUse = new ParkingUse();
        parkingUse.setUserId(userId);
        parkingUse.setCarNumber(carNumber);
        parkingUse.setParkingId(parkingId);
        parkingUse.setUseType(useType);
        parkingUse.setTotalFee(totalFee);
/*        DateUtil.stringToDate(startTime);
        DateUtil.stringToDate(endTime);*/
        parkingUse.setStartTime(startTime);
        parkingUse.setEndTime(endTime);
        boolean success = parkingUseService.save(parkingUse);
        return success ? AjaxResult.success(parkingUse) : AjaxResult.fail("新增车位使用记录失败");
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "【管理员】更新车位使用记录", notes = "根据ID更新车位使用记录")
    public AjaxResult updateParkingUse(@RequestHeader("Authorization") String token,
            @ApiParam(value = "使用记录ID", required = true, example = "1")
            @PathVariable Long id,

            @ApiParam(value = "用户ID", example = "1")
            @RequestParam(required = false) Long userId,

            @ApiParam(value = "车牌号", example = "1")
            @RequestParam(required = false) String carNumber,

            @ApiParam(value = "车位ID", example = "1")
            @RequestParam(required = false) Long parkingID,

            @ApiParam(value = "使用类型", example = "月租")
            @RequestParam(required = false) String useType,

            @ApiParam(value = "总费用", example = "158.5")
            @RequestParam(required = false) Double totalFee,

            @ApiParam(value = "开始使用时间", example = "2025-1-1 00:00:00")
            @RequestParam(value = "startTime", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime,

            @ApiParam(value = "使用结束时间", example = "2025-1-2 12:00:00")
            @RequestParam(value = "endTime", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) {
        ParkingUse parkingUse = new ParkingUse();
        parkingUse.setId(id);
        parkingUse.setUserId(userId);
        parkingUse.setCarNumber(carNumber);
        parkingUse.setParkingId(parkingID);
        parkingUse.setUseType(useType);
        parkingUse.setTotalFee(totalFee);
        parkingUse.setStartTime(startTime);
        parkingUse.setEndTime(endTime);
        parkingUse.setUpdateTime(DateUtil.dateToString(new Date()));
        boolean success = parkingUseService.updateById(parkingUse);
        return success ? AjaxResult.success("更新成功") : AjaxResult.fail("更新失败");
    }

    /*
        不允许删除车位
     */
}
